﻿using System.Reflection;

namespace JGSY.SerialCommunication.UpperComputer.Core.AOP
{
    /// <summary>
    /// Net内置DispatchProxy的动态代理
    /// </summary>
    public class DynamicProxy<T> : DispatchProxy where T : class
    {
        private T _target;
        public static T Create(T target)
        {
            //DynamicProxy<T> proxy = Create<T, DynamicProxy<T>>() as DynamicProxy<T>;
            //if (proxy == null) { /* 处理失败 */ }
            //proxy._target = targte;
            ////强制类型转换(T)(object)  值为 null 抛异常  
            ////类型安全转换 as	返回 null 不抛异常	一次 isinst 指令	不确定类型，需判空
            //return (T)(object)proxy;

            // 1. 拿到代理实例
            var proxy = Create<T, DynamicProxy<T>>() as DynamicProxy<T>;
            // 2. 注入真实对象
            proxy._target = target;
            // 3. 返回接口
            return (T)(object)proxy;

        }

        protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
        {
            Console.WriteLine($"[Log] 进入方法: {targetMethod.Name}, 参数: {string.Join(", ", args)}");
            try
            {
                var result = targetMethod.Invoke(_target, args);
                Console.WriteLine($"[Log] 退出方法: {targetMethod.Name}, 返回值: {result}");
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[Error] 方法 {targetMethod.Name} 抛出异常: {ex.Message}");
                throw;
            }
        }


    }

}
